package com.hhkj.admin.student.service.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.hhkj.admin.course.domain.Course;
import com.hhkj.admin.course.service.biz.SaleCourseBizService;
import com.hhkj.admin.student.common.cont.StudentConst;
import com.hhkj.admin.student.model.dopo.StudentCoursePo;
import com.hhkj.admin.student.model.dopo.StudentPo;
import com.hhkj.admin.student.model.model.SaleStudentFreeExportModel;
import com.hhkj.admin.student.model.req.SaleStudentReq;
import com.hhkj.admin.student.model.res.SaleStudentCourseRes;
import com.hhkj.admin.student.model.res.SaleStudentRes;
import com.hhkj.admin.student.service.base.StudentService;
import com.hhkj.admin.student.service.biz.SaleStudentBizService;
import com.hhkj.admin.student.service.extend.StudentCourseExtendService;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.excl.utils.ExcelUtils;
import com.ruoyi.common.utils.paging.PageInfoUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * SaleStudentBizServiceImpl
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2024/1/16 21:39
 */
@Service
public class SaleStudentBizServiceImpl implements SaleStudentBizService {

    @Autowired
    private StudentService studentService;
    @Autowired
    private SaleCourseBizService saleCourseBizService;
    @Autowired
    private StudentCourseExtendService studentCourseExtendService;

    @Override
    public Workbook createFreeExcel(SaleStudentReq req) {
        List<StudentPo> studentFreeList;
        List<Course> courseList = saleCourseBizService.listFree();
        if (CollectionUtil.isEmpty(courseList)) {
            studentFreeList = new ArrayList<>();
        } else {
            List<Long> courseIdList = courseList.stream().map(Course::getId).collect(Collectors.toList());
            req.setCourseIdList(courseIdList);
            studentFreeList = studentService.listPoByDo(req);
        }
        List<SaleStudentRes> studentResList = BeanUtil.copyToList(studentFreeList, SaleStudentRes.class);
        this.supplyCourse(studentResList);
        List<SaleStudentFreeExportModel> modelResList = studentResList.stream()
                .map(studentRes -> {
                    SaleStudentFreeExportModel modelRes = new SaleStudentFreeExportModel(studentRes.getName(),
                            studentRes.getIdCard(), studentRes.getPhone(), DateUtil.format(studentRes.getCreateTime(), DatePattern.NORM_DATETIME_MINUTE_PATTERN));
                    modelRes.setCourses(generateStudentFreeCourse(studentRes.getCourseList()));
                    return modelRes;
                }).collect(Collectors.toList());

        return ExcelUtils.createExcelWorkbook(
                modelResList,
                SaleStudentFreeExportModel.EXCEL_TITLE,
                SaleStudentFreeExportModel.EXCEL_TITLE,
                SaleStudentFreeExportModel.class);
    }

    /**
     * 创建课程信息
     *
     * @param courseResList 课程信息列表
     * @return 封装的课程信息
     */
    private String generateStudentFreeCourse(List<SaleStudentCourseRes> courseResList) {
        List<String> courseInfoList = courseResList.stream()
                .map(courseRes -> {
                    String remark = StrUtil.EMPTY;
                    if (StudentConst.AuditCode.STATUS_NO_CHECK.getCode().equals(courseRes.getStatus())) {
                        remark = StudentConst.AuditCode.STATUS_NO_CHECK.getName();
                    }
                    if (StudentConst.AuditCode.STATUS_PASS.getCode().equals(courseRes.getStatus())
                            || (StudentConst.AuditCode.STATUS_OUT_TIME.getCode().equals(courseRes.getStatus()))) {
                        remark = (ObjectUtil.isNotEmpty(courseRes.getStartDate()) ? DateUtil.format(courseRes.getCreateTime(), DatePattern.NORM_DATE_PATTERN) : "-")
                                + (ObjectUtil.isNotEmpty(courseRes.getLineDate()) ? ("到" + DateUtil.format(courseRes.getLineDate(), DatePattern.NORM_DATE_PATTERN)) : "无过期时间");
                    }
                    if ((StudentConst.AuditCode.STATUS_DISABLED.getCode().equals(courseRes.getStatus()))) {
                        remark = StudentConst.AuditCode.STATUS_DISABLED.getName();
                    }
                    return courseRes.getCourseName() + "(" + remark + ")";
                })
                .collect(Collectors.toList());
        return CollectionUtil.join(courseInfoList, "\n");
    }

    @Override
    public PageInfo<SaleStudentRes> pagingFree(SaleStudentReq req) {
        List<Course> courseList = saleCourseBizService.listFree();
        if (CollectionUtil.isEmpty(courseList)) {
            return PageInfoUtils.emptyPage(SaleStudentRes.class);
        }
        List<Long> courseIdList = courseList.stream().map(Course::getId).collect(Collectors.toList());
        req.setCourseIdList(courseIdList);
        PageUtils.startPageBody(req);
        List<StudentPo> studentPoList = studentService.listPoByDo(req);
        PageInfo<SaleStudentRes> resPageInfo = PageInfoUtils.toPageInfo(studentPoList, SaleStudentRes.class);
        this.afterPaging(resPageInfo.getList());
        return resPageInfo;
    }

    /**
     * 分页列表后置处理
     *
     * @param recordList 纪录列表信息
     */
    private void afterPaging(List<SaleStudentRes> recordList) {
        if (CollectionUtil.isEmpty(recordList)) {
            return;
        }
        this.supplyCourse(recordList);
    }

    /**
     * 补充记录的科目报名列表信息
     *
     * @param recordList 记录列表
     */
    private void supplyCourse(List<SaleStudentRes> recordList) {
        if (CollectionUtil.isEmpty(recordList)) {
            return;
        }
        List<Long> studentIdList = recordList.stream().map(SaleStudentRes::getId).collect(Collectors.toList());
        List<StudentCoursePo> studentCoursePoList = studentCourseExtendService.listPoByStudentIdListAll(studentIdList);
        Map<Long, List<SaleStudentCourseRes>> studentCourseResListByStudentIdMap = studentCoursePoList.stream()
                .map(studentCoursePo -> BeanUtil.toBean(studentCoursePo, SaleStudentCourseRes.class))
                .collect(Collectors.groupingBy(SaleStudentCourseRes::getStudentId));
        for (SaleStudentRes studentRes : recordList) {
            if (studentCourseResListByStudentIdMap.containsKey(studentRes.getId())) {
                studentRes.setCourseList(studentCourseResListByStudentIdMap.get(studentRes.getId()));
            }
        }
    }
}
